# -*- coding: utf-8 -*-
from scpy.logger import get_logger
import os
import sys
import tornado
from util.pgutil import PgUtil
import json
import numpy as np
from analysis.recruitment_info_ana import *
from collections import Counter

reload(sys)
sys.setdefaultencoding('utf-8')

logger = get_logger(__file__)

CURRENT_PATH = os.path.dirname(__file__)
if CURRENT_PATH:
    CURRENT_PATH = CURRENT_PATH + "/"


class MonitorCompanyListHandler(tornado.web.RequestHandler):
    def get(self):
        pg = PgUtil()
        random_str = self.get_argument('callback','')
        result = pg.query_all_sql('select id,company_name from recruitment_monitor_company')
        self.write(json.dumps(result,ensure_ascii=False,indent=1))
        # self.write(random_str + "(" + json.dumps(result,ensure_ascii=False,indent=1) + ")")


class SearchCompanyRecruitmentInfoHandler(tornado.web.RequestHandler):
    def get(self):
        company_name = self.get_argument('companyName')
        random_str = self.get_argument('callback','')
        result_dic = self.build_info_dic(company_name)
        self.write(json.dumps(result_dic,ensure_ascii=False,indent=1))
        # self.write(random_str + "(" + json.dumps(result_dic,ensure_ascii=False,indent=1) + ")")

    def build_info_dic(self, company_name):
        infoDic = dict()
        pg = PgUtil()
        # company avg salary
        try:
            _avgSalaryRes = pg.select_sql(SEARCH_COMPANY_AVG_SALARY,(company_name,))
            if len(_avgSalaryRes) > 0:
                companyAvgSalay = _avgSalaryRes[0]
            else:
                companyAvgSalay = None
            infoDic['companyAvgSalay'] = round(companyAvgSalay,2)
        except Exception, e:
            logger.error('FUN[build_info_dic] get company avg salary failed for %s'%str(e))
            infoDic['companyAvgSalay'] = None

        # company degree dis
        try:
            _degreeDisRes = pg.select_all_sql(SEARCH_COMPANY_DEGREE_DIS,(company_name,))
            _degreeDisList = list()
            if len(_degreeDisRes) > 0:
                for item in _degreeDisRes:
                    _degreeDisList.append({
                        'key':item[0],
                        'value':item[1]
                    })
            infoDic['companyDegreeDis'] = _degreeDisList
        except Exception, e:
            logger.error('FUN[build_info_dic] get company degree distribution failed for %s'%str(e))
            infoDic['companyDegreeDis'] = []

        # company working years avg
        try:
            _workingYearsAvgRes = pg.select_sql(SEARCH_COMPANY_AVG_WORKING_YEARS,(company_name,))
            if len(_workingYearsAvgRes) > 0:
                companyWorkingYearsAvg = _workingYearsAvgRes[0]
            else:
                companyWorkingYearsAvg = None
            infoDic['companyWorkingYearsAvg'] = round(companyWorkingYearsAvg,2)
        except Exception, e:
            logger.error('FUN[build_info_dic] get company working years failed for %s'%str(e))
            infoDic['companyWorkingYearsAvg'] = None

        # company category_type dis
        try:
            _categoryTypeDisRes = pg.select_all_sql(SEARCH_COMPANY_CATEGORYTYPE_DIS,(company_name,))
            _categoryTypeDisList = list()
            if len(_categoryTypeDisRes) > 0:
                for item in _categoryTypeDisRes:
                    _categoryTypeDisList.append({
                        'key':item[0],
                        'value':item[1]
                    })
            infoDic['companyCategoryTypeDis'] = _categoryTypeDisList
        except Exception, e:
            logger.error('FUN[build_info_dic] get company category type distribution failed for %s'%str(e))
            infoDic['companyCategoryTypeDis'] = []

        # company category dis group by category_type
        try:
            _categoryDisRes = pg.select_all_sql(SEARCH_COMPANY_CATEGORY_DIS,(company_name,))
            _categoryDisDict = dict()
            if len(_categoryDisRes) > 0:
                for item in _categoryDisRes:
                    if item[0] not in _categoryDisDict.keys():
                        _categoryDisDict[item[0]] = list()
                        _categoryDisDict[item[0]].append({
                            'key': item[1],
                            'value': item[2],
                        })
                    else:
                        _categoryDisDict[item[0]].append({
                            'key': item[1],
                            'value': item[2],
                        })
            infoDic['companyCategoryDis'] = _categoryDisDict
        except Exception, e:
            logger.error('FUN[build_info_dic] get company category group by category_type distribution failed for %s'%str(e))
            infoDic['companyCategoryDis'] = {}

        # company category_type dis by time step
        try:
            _categoryTypeTimeStepDisRes = pg.select_all_sql(SEARCH_COMPANY_CATEGORYTYPE_BY_TIME_STEP,(company_name,))
            _categoryTypeTimeStepDisDict = dict()
            if len(_categoryTypeTimeStepDisRes) > 0:
                for item in _categoryTypeTimeStepDisRes:
                    if item[0] not in _categoryTypeTimeStepDisDict.keys():
                        _categoryTypeTimeStepDisDict[item[0]] = list()
                        _categoryTypeTimeStepDisDict[item[0]].append({
                            'key': item[1],
                            'value': item[2],
                        })
                    else:
                        _categoryTypeTimeStepDisDict[item[0]].append({
                            'key': item[1],
                            'value': item[2],
                        })
            infoDic['CompanyCategoryTypeTimeStepDis'] = _categoryTypeTimeStepDisDict
        except Exception, e:
            logger.error('FUN[build_info_dic] get company category_type distribution group by time step failed for %s'%str(e))
            infoDic['CompanyCategoryTypeTimeStepDis'] = {}

        return infoDic


# class SearchCompanyRecruitmentTimeStepHandler(tornado.web.RequestHandler):
#     def get(self):
#         company_name = self.get_argument('companyName')
#         result = self.build_time_step_info(company_name)
#         self.write(json.dumps(result,ensure_ascii=False,indent=1))
#
#     def build_time_step_info(self, company_name):
#         YEARS_LIST = ['2013', '2014', '2015', '2016']
#         MONTH_LIST = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
#         time_step_list = list()
#         time_step_info = dict()
#         for year in YEARS_LIST:
#             for month in MONTH_LIST:
#                 time_step_list.append(year + '-' + month)
#         # time step info
#         for time_step_item in time_step_list:
#             this_month_result_list = pg.select_all_sql(SEARCH_COMPANY_INFO_BY_TIME_STEP_THIS_MONTH,(company_name, time_step_item))
#             pre_month_result_list = pg.select_all_sql(SEARCH_COMPANY_INFO_BY_TIME_STEP_PRE_MONTH,(company_name, time_step_item))
#             if len(pre_month_result_list) == 0 and len(this_month_result_list) == 0:
#                 time_step_info[time_step_item] = {
#                     'des': u'无历史招聘信息',
#                 }
#             elif len(pre_month_result_list) == 0 and len(this_month_result_list) != 0:
#                 time_step_info[time_step_item] = {
#                     'des': u'无历史招聘信息(初始化)',
#                     # 'originInfo': this_month_result_list,
#                 }
#             elif len(pre_month_result_list) != 0 and len(this_month_result_list) == 0:
#                 time_step_info[time_step_item] = {
#                     'des': u'本月无招聘信息',
#                 }
#             else:
#                 pre_month_info = self.cal_month_info(pre_month_result_list)
#                 this_month_info = self.cal_month_info(this_month_result_list)
#                 resultInfo = self.month_recruitment_info_compare(pre_month_info, this_month_info)
#                 # resultInfo['originInfo'] = this_month_result_list
#                 time_step_info[time_step_item] = resultInfo
#
#         # similar company info
#         category_type_query_result = pg.select_all_sql(SEARCH_SIMILAR_COMPANY_CATEGORY_TYPE_DIS,(company_name,))
#         category_type_list = list()
#         for item in category_type_query_result:
#             category_type_list.append({
#                 'key': item[0],
#                 'value': item[1]
#             })
#
#         degree_type_query_result = pg.select_all_sql(SEARCH_SIMILAR_COMPANY_DEGREE_DIS,(company_name,))
#         degree_dis_list = list()
#         for item in degree_type_query_result:
#             degree_dis_list.append({
#                 'key': item[0],
#                 'value': item[1]
#             })
#
#         time_step_info['similarCompanyStaticInfo'] = {
#             'salaryAvg':pg.select_sql(SEARCH_SIMILAR_COMPANY_AVG_SALARY,(company_name,))[0],
#             'workingYearsAvg':pg.select_sql(SEARCH_SIMILAR_COMPANY_AVG_WORKING_YEARS,(company_name,))[0],
#             'categoryTypeDis':category_type_list,
#             'degreeDis':degree_dis_list,
#         }
#         time_step_info = sorted(time_step_info.iteritems(), key=lambda d: d[0], reverse=False)
#
#         return time_step_info
#
#     def cal_month_info(self, month_result_list):
#         salaryList = list()
#         degreeList = list()
#         workingYearsList = list()
#         categoryTypeList = list()
#         categoryList = list()
#         cityList = list()
#         preInfo = dict()
#         for infoDic in month_result_list:
#             salaryList.append(infoDic.get('salary'))
#             degreeList.append(infoDic.get('degree'))
#             workingYearsList.append(infoDic.get('working_years'))
#             categoryTypeList.append(infoDic.get('category_type'))
#             categoryList.append(infoDic.get('category'))
#             cityList.append(infoDic.get('city'))
#         preInfo['salaryArray'] = np.array(salaryList)
#         if len(salaryList) < 1:
#             preInfo['salaryAvg'] = None
#             preInfo['salaryStd'] = None
#         else:
#             preInfo['salaryAvg'] = np.average(preInfo['salaryArray'])
#             preInfo['salaryStd'] = np.std(preInfo['salaryArray'])
#         preInfo['degreeInfo'] = Counter(degreeList)
#         preInfo['workingYearsArray'] = np.array(workingYearsList)
#         if len(workingYearsList) < 1:
#             preInfo['workingYearsAvg'] = None
#             preInfo['workingYearsStd'] = None
#         else:
#             preInfo['workingYearsAvg'] = np.average(preInfo['workingYearsArray'])
#             preInfo['workingYearsStd'] = np.std(preInfo['workingYearsArray'])
#         preInfo['categoryTypeInfo'] = Counter(categoryTypeList)
#         preInfo['categoryInfo'] = Counter(categoryList)
#         preInfo['cityInfo'] = Counter(cityList)
#
#         return preInfo
#
#     def month_recruitment_info_compare(self, pre_month_info, this_month_info):
#         compareResultDict = dict()
#         # salary compare
#         if this_month_info.get('salaryAvg') >= (pre_month_info.get('salaryAvg')+pre_month_info.get('salaryStd')):
#             compareResultDict['salaryDes'] = u'该月招聘工资值偏高'
#         elif this_month_info.get('salaryAvg') <= (pre_month_info.get('salaryAvg')-pre_month_info.get('salaryStd')):
#             compareResultDict['salaryDes'] = u'该月招聘工资值偏低'
#         else:
#             compareResultDict['salaryDes'] = u'该月招聘工资值在正常范围内'
#         # working years compare
#         if this_month_info.get('workingYearsAvg') >= (pre_month_info.get('workingYearsAvg')+pre_month_info.get('workingYearsStd')):
#             compareResultDict['workingYearsDes'] = u'该月招聘工作经验要求偏高'
#         elif this_month_info.get('workingYearsAvg') <= (pre_month_info.get('workingYearsAvg')-pre_month_info.get('workingYearsStd')):
#             compareResultDict['workingYearsDes'] = u'该月招聘工作经验要求偏低'
#         else:
#             compareResultDict['workingYearsDes'] = u'该月招聘工作经验要求在正常范围内'
#         # counter compare
#         # city
#         city_compare_dict = self.compare_dict(pre_month_info.get('cityInfo'), this_month_info.get('cityInfo'))
#         if len(city_compare_dict['addingKeys']) != 0:
#             compareResultDict['cityAddingDes'] = u'新增工作地点为:'
#             for city in city_compare_dict['addingKeys']:
#                 compareResultDict['cityAddingDes'] += city + ' '
#         if len(city_compare_dict['sameKeysDetection']) != 0:
#             compareResultDict['cityDetectionDes'] = u'工作地点分布出现较大变化:\n'
#             for item in city_compare_dict['sameKeysDetection']:
#                 if item['percentageDiff'] < 0:
#                     compareResultDict['cityDetectionDes'] += u'%s 地区职位比例大量减少\n'%item['key']
#                 if item['percentageDiff'] > 0:
#                     compareResultDict['cityDetectionDes'] += u'%s 地区职位比例大量增加\n'%item['key']
#         # category
#         category_compare_dict = self.compare_dict(pre_month_info.get('categoryInfo'), this_month_info.get('categoryInfo'))
#         if len(category_compare_dict['addingKeys']) != 0:
#             compareResultDict['categoryAddingDes'] = u'新增职位类型:'
#             for category in category_compare_dict['addingKeys']:
#                 compareResultDict['categoryAddingDes'] += category + ' '
#         if len(category_compare_dict['sameKeysDetection']) != 0:
#             compareResultDict['categoryDetectionDes'] = u'职位类型需求出现较大变化:\n'
#             for item in category_compare_dict['sameKeysDetection']:
#                 if item['percentageDiff'] < 0:
#                     compareResultDict['categoryDetectionDes'] += u'%s 职位类型比例大量减少\n'%item['key']
#                 if item['percentageDiff'] > 0:
#                     compareResultDict['categoryDetectionDes'] += u'%s 职位类型比例大量增加\n'%item['key']
#         # category_type
#         category_type_compare_dict = self.compare_dict(pre_month_info.get('categoryTypeInfo'), this_month_info.get('categoryTypeInfo'))
#         if len(category_type_compare_dict['addingKeys']) != 0:
#             compareResultDict['categoryTypeAddingDes'] = u'新增职位方向:'
#             for category_type in category_type_compare_dict['addingKeys']:
#                 compareResultDict['categoryTypeAddingDes'] += category_type + ' '
#         if len(category_type_compare_dict['sameKeysDetection']) != 0:
#             compareResultDict['categoryTypeDetectionDes'] = u'职位方向需求出现较大变化:\n'
#             for item in category_type_compare_dict['sameKeysDetection']:
#                 if item['percentageDiff'] < 0:
#                     compareResultDict['categoryTypeDetectionDes'] += u'%s 职位方向比例大量减少\n'%item['key']
#                 if item['percentageDiff'] > 0:
#                     compareResultDict['categoryTypeDetectionDes'] += u'%s 职位方向比例大量增加\n'%item['key']
#         return compareResultDict
#
#     def compare_dict(self, pre_dict, this_dict):
#         pre_dict_keys = pre_dict.keys()
#         this_dict_keys = this_dict.keys()
#         same_keys_list = list()
#         missing_keys_list = list()
#         add_keys_list = list()
#         for pre_item in pre_dict_keys:
#             if pre_item in this_dict_keys:
#                 same_keys_list.append(pre_item)
#                 this_dict_keys.remove(pre_item)
#             else:
#                 missing_keys_list.append(pre_item)
#         add_keys_list = this_dict_keys
#         # percentage detect
#         same_keys_detection = list()
#         for key in same_keys_list:
#             pre_key_percentage = pre_dict[key]/float(sum(pre_dict.values()))
#             this_key_percentage = this_dict[key]/float(sum(this_dict.values()))
#             if (this_key_percentage-pre_key_percentage) > 0.25 or (this_key_percentage-pre_key_percentage) < -0.25:
#                 same_keys_detection.append({
#                     'key': key,
#                     'percentageDiff': (this_key_percentage-pre_key_percentage),
#                 })
#         return {
#             'sameKeys': same_keys_list,
#             'missingKeys': missing_keys_list,
#             'addingKeys': add_keys_list,
#             'sameKeysDetection': same_keys_detection,
#         }
#
#     def trans_query_result_timestamp_type(self, result_list):
#         pass


class SearchCategoryTypeInfoHandler(tornado.web.RequestHandler):
    def get(self):
        pg = PgUtil()
        random_str = self.get_argument('callback','')
        result = self.build_category_type_info()
        self.write(json.dumps(result, ensure_ascii=False, indent=1))

    def build_category_type_info(self):
        categoryTypeInfo = {
            'categoryTypeSalaryAvg': pg.query_all_sql(SEARCH_CATEGORYTYPE_SALARY_AVG),
            'categoryTypeWorkingYearsAvg': pg.query_all_sql(SEARCH_CATEGORYTYPE_WORKING_YEARS_AVG),
            'categoryTypeNumByTime': pg.query_all_sql(SEARCH_CATEGORYTYPE_DIS_BY_TIME_STEP),
            'categoryTypeLocationDis': pg.query_all_sql(SEARCH_CATEGORYTYPE_LOCATION_DIS),
        }
        return categoryTypeInfo


def build_time_step_info(company_name):
    YEARS_LIST = ['2013', '2014', '2015', '2016']
    # YEARS_LIST = ['2015', '2016']
    MONTH_LIST = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
    time_step_list = list()
    for year in YEARS_LIST:
        for month in MONTH_LIST:
            time_step_list.append(year + '-' + month)
    for time_step_item in time_step_list:
        this_month_result_list = pg.select_all_sql(SEARCH_COMPANY_INFO_BY_TIME_STEP_PRE_MONTH, (company_name, time_step_item))
        pre_month_result_list = pg.select_all_sql(SEARCH_COMPANY_INFO_BY_TIME_STEP_THIS_MONTH, (company_name, time_step_item))

if __name__ == '__main__':
    company_name = u'杭州誉存科技有限公司'
    build_time_step_info(company_name)